<?php


namespace app\api\controller;


use app\common\controller\Api;
use app\common\controller\Backend;
use think\Db;
use think\Exception;

class Goods extends Api
{


    /*获取规格列表 */
    public function skuList()
    {
        try{
            $goodId=input('goods_id','','int');//商品ID
            if(empty($goodId)){
                $this->error('商品ID不能为空！');
            }

            $goods_info=Db::name('shopro_goods')->where(['id'=>$goodId])->find();
            if(empty($goods_info)){
                $this->error('商品不存在！');
            }

            $list=Db::name('shopro_goods_sku')->field('id,name,pid')->where(['goods_id'=>$goodId])->select();
            $father=$son=$find=[];
            if(!empty($list)){
                foreach ($list as $k=>$v){
                    if($v['pid']==0){
                        $father[]=$v;
                        continue;
                    }
                    $son[$v['pid']][]=$v;
                }
                if(!empty($father)){
                    foreach ($father as $k=>$v){
                        if(isset($son[$v['id']])){
                            $father[$k]['children']=$son[$v['id']];
                        }
                    }
                }
            }

            $skuprice=Db::name('shopro_goods_sku_price')->field('goods_sku_ids,goods_id,stock,stock_warning,sales,sn,weight,price,goods_sku_text')->where(['goods_id'=>$goodId,'status'=>'up'])->select();
            $data['skulist']=$father;
            $data['skuprice']=$skuprice;
            $this->success('success',$data,0);
        }catch (Exception $e){
            $msg=$e->getMessage();
            $this->error($msg);
        }
    }


    //待核销的订单
    public function writeOff(){
        try{
            $status=input('status','1','int');
            $size=input('size','10','int');
            $page=input('page','1','int');

            if(empty($status)){
                $this->error('核销状态不能为空');
            }
            $limit=($page-1)*$size;
            $maps=[];
            $order="createtime desc";

            //当前登录用户的门诊店ID
            $store_id=Db::name('shopro_user_store')->where(['user_id'=>$this->auth->id])->value('store_id');
            $maps['clinc_score_id']=$store_id;

            //核销状态
            switch ($status){
                case 1://1全部
                    $maps['status']=['in',"1,2"];
                    break;
                case 2:// 2待核销
                    $maps['status']=1;
                    break;
                case 3://3已核销
                    $maps['status']=2;
                    break;
                default:
                    $this->error('未知状态');
            }

            $list=Db::name('shopro_order')
                ->field('clinc_score_id,status,id,order_sn,total_amount,pay_type,createtime,operation_uid')
                ->where($maps)
                ->order($order)
                ->limit($limit,$size)
                ->select();

            $total=Db::name('shopro_order')->where($maps)->count();
            $new_list=[];
            if(!empty($list)){
                foreach ($list as $k=>$v){
                    $sonList=Db::name('shopro_order_item')->field('goods_image,goods_title,id')->where(['order_id '=>$v['id']])->select();
                    if(!empty($sonList)){
                        foreach ($sonList as &$vd){
                            $vd['goods_image']=cdnurl($vd['goods_image']);
                        }
                    }
                    $new_list[]=[
                        'order_id'=>$v['id'],
                        'order_sn'=>$v['order_sn'],
                        'total_amount'=>$v['total_amount'],
                        'pay_type'=>$v['pay_type'],
                        'createtime'=>date("Y-m-d H:i:s",$v['createtime']),
                        'status'=>$v['status'],
                        'goods_num'=>count($sonList),
                        'goods_image'=>!empty($sonList)?array_column($sonList,'goods_image'):[],
                    ];
                }
            }
            $data=[
                'total'=>$total,
                'list'=>$new_list
            ];
            $this->success('success',$data,0);
        }catch (Exception $e){
            $msg=$e->getMessage();
            $this->error($msg);
        }
    }


    //核销详情
    public function writeOffdetail(){
        $order_id=input('order_id','','int');//核销订单ID

        if(empty($order_id)){
            $this->error('核销订单ID不能为空！',['state'=>1]);
        }

        //当前登录用户的门诊店ID
        $store_id=Db::name('shopro_user_store')->where(['user_id'=>$this->auth->id])->value('store_id');
        $detail=Db::name('shopro_order')->field('id,order_sn,user_id,total_amount,pay_type,status,operation_uid')
            ->where(['id'=>$order_id,'clinc_score_id'=>$store_id])->find();

        if(!empty($detail)){
            $order_info=Db::name('shopro_order_item')->field('goods_title,goods_image,goods_price,goods_num')->where(['order_id'=>$order_id])->select();
            if(!empty($order_info)){
                foreach ($order_info as &$v){
                    $v['goods_image']=!empty($v['goods_image'])?cdnurl($v['goods_image']):'';
                }
            }
            $detail['order_info']=$order_info;
            $user=Db::name('user')->field('username,mobile')->where(['id'=>$detail['user_id']])->find();
            $detail['username']=!empty($user['username'])?$user['username']:'';
            $detail['mobile']=!empty($user['mobile'])?$user['mobile']:'';
            $operation_user=Db::name('user')->field('nickname')->where(['id'=>$detail['operation_uid']])->find();
            $detail['operation_name']=!empty($operation_user['nickname'])?$operation_user['nickname']:'';
            $detail['goods_counts']=!empty($order_info)?array_sum(array_column($order_info,'goods_num')):0;
        }
        $this->success('success',$detail,0);
    }


    //确认核销
    public function confirmWriteOff(){
        $order_item_id=input('order_id','','int');//核销订单ID
        if(empty($order_item_id)){
            $this->error('核销订单ID不能为空！',['state'=>1]);
        }

        //当前登录用户的门诊店ID
        $store_id=Db::name('shopro_user_store')->where(['user_id'=>$this->auth->id])->value('store_id');

        $detail=Db::name('shopro_order')->where(['id'=>$order_item_id,'clinc_score_id'=>$store_id])->find();
        if(empty($detail)){
            $this->error('核销订单不存在！',['state'=>2]);
        }

        if($detail['status']!=1){
            $this->error('核销状态不正确！',['state'=>3]);
        }

        //后期加上用户或者管理员
        Db::startTrans();
        $r0=Db::name('shopro_order')->where(['id'=>$order_item_id])->update([
            'status'=>2,
            'operation_uid'=>$this->auth->id,//核销管理员id
            'updatetime'=>time(),
        ]);
        if(!$r0){
            Db::rollback();
            $this->error('核销失败！',['state'=>4],0);
        }

        $r1=Db::name('shopro_order_item')->where(['order_id'=>$order_item_id])->update([
            'wiped_status'=>1,
            'operation_uid'=>$this->auth->id,//核销管理员id
            'updatetime'=>time(),
        ]);
        if(!$r1){
            Db::rollback();
            $this->error('核销失败！',['state'=>4]);
        }
        Db::commit();
        $this->success('核销成功',['state'=>0],0);
    }


    //搜索核销
    public function queryWriteOff(){
        $mobile=input('mobile','','trim');//核销订单ID

        //输入手机号的时候
        if(!empty($mobile)){
            $user=Db::name('user')->where(['mobile'=>$mobile])->find();
            if(empty($user)){
                $this->error('核销手机号不存在！',['state'=>1]);
            }
            $userId=$user['id'];
            $maps['user_id']=$userId;
            $maps['status']=['in',"1"];
        }else{
            $maps['status']=['in',"2"];
        }

        $store_id=Db::name('shopro_user_store')->where(['user_id'=>$this->auth->id])->value('store_id');

        if(!empty($store_id)){
            $maps['clinc_score_id']=$store_id;//当前登录用户的门店ID
        }else{
            $maps['clinc_score_id']='xxxxx';//不存在就为空
        }

//        $maps['status']=['in',"1,2"];
        $order="status asc,createtime desc";

        $list=Db::name('shopro_order')
            ->field('clinc_score_id,status,id,order_sn,user_id,total_amount,pay_type,createtime,updatetime,operation_uid')
            ->where($maps)
            ->order($order)
            ->select();

        $dai_list=$yi_list=[];
        if(!empty($list)){
                foreach ($list as $k=>$v){
                    $operation_user=Db::name('user')->field('nickname')->where(['id'=>$v['operation_uid']])->find();
                    $customer_user=Db::name('user')->field('nickname')->where(['id'=>$v['user_id']])->find();
                    if(empty($mobile)){
                        $mobiles = Db::name('user')->where(['id'=>$v['user_id']])->value('mobile');
                    }
                    $sonList=Db::name('shopro_order_item')->field('goods_image,goods_title,goods_num')->where(['order_id '=>$v['id']])->select();
                    if(!empty($sonList)){
                        foreach ($sonList as &$vd){
                            $vd['goods_image']=cdnurl($vd['goods_image']);
                        }
                    }
                    $arr=[
                        'order_id'=>$v['id'],
                        'mobile'=>$mobile ? $mobile : $mobiles,
                        'order_sn'=>$v['order_sn'],
                        'total_amount'=>$v['total_amount'],
                        'pay_type'=>$v['pay_type'],
                        'createtime'=>date('Y-m-d H:i:s',$v['createtime']),
                        'updatetime'=>date('Y-m-d H:i:s',$v['updatetime']),
                        'status'=>$v['status'],
                        'operation_name'=>!empty($operation_user['nickname'])?$operation_user['nickname']:'',
                        'username'=>!empty($customer_user['nickname'])?$customer_user['nickname']:'',
                        'goods_counts'=>count($sonList),
                        'goods_info'=>!empty($sonList)?$sonList:[],
                    ];
                    if($v['status']==1){
                        $dai_list[]=$arr;
                    }
                    if($v['status']==2){
                        $yi_list[]=$arr;
                    }
                 }
            }
        $data=[
            'wait_list'=>$dai_list,
            'finished_list'=>$yi_list,
        ];
        $this->success('success',$data,0);
    }


    //自提列表
    public function selfetchList(){
        try{
            $status=input('status','1','int');//
            $size=input('size','10','int');
            $page=input('page','1','int');

            if(empty($status)){
                $this->error('搜索状态不能为空');
            }

            $limit=($page-1)*$size;
            $maps=[];
            $order="createtime desc";

            $maps['user_id ']=$this->auth->id;//当前登录的用户ID
            $maps['clinc_score_id ']=['>','0'];//当前登录的用户ID

            //核销状态
            switch ($status){
                case 1://1待自提
                    $maps['status']=1;
                    break;
                case 2:// 2已完成
                    $maps['status']=2;
                    break;
                case 3://3已取消
                    $maps['status']=-1;
                    break;
                default:
                    $this->error('未知状态');
            }

            $list=Db::name('shopro_order')
                ->field('clinc_score_id,user_id,status,id,order_sn,total_amount,pay_type,pay_fee,createtime,updatetime,operation_uid')
                ->where($maps)
                ->order($order)
                ->limit($limit,$size)
                ->select();

            $total=Db::name('shopro_order')->where($maps)->count();
            $arr=[1=>'待自提',2=>'已完成',-1=>'已取消'];
            $new_list=[];
            if(!empty($list)){
                foreach ($list as $k=>$v){
                    $sonList=Db::name('shopro_order_item')->field('goods_image,goods_title,goods_num,goods_price')->where(['order_id '=>$v['id']])->select();
                    if(!empty($sonList)){
                        foreach ($sonList as &$vd){
                            $vd['goods_image']=cdnurl($vd['goods_image']);
                        }
                    }
                    $store_info=Db::name('shopro_store')->field('name,phone,province_name,city_name,area_name,address')->where(['id'=>$v['clinc_score_id'],'status'=>1])->find();
                    $new_list[]=[
                        'order_id'=>$v['id'],
                        'clinc_score_id'=>$v['clinc_score_id'],
                        'status_name'=>isset($arr[$v['status']])?$arr[$v['status']]:'未知',
                        'order_sn'=>$v['order_sn'],
                        'total_amount'=>$v['total_amount'],
                        'pay_type'=>$v['pay_type'],
                        'createtime'=>date('Y-m-d H:i:s',$v['createtime']),
                        'updatetime'=>date('Y-m-d H:i:s',$v['updatetime']),
                        'status'=>$v['status'],
                        'goods_count'=>count($sonList),
                        'store_info'=>[
                            'store_name'=>!empty($store_info['name'])?$store_info['name']:'',
                            'store_phone'=>!empty($store_info['phone'])?$store_info['phone']:'',
                            'province_name'=>!empty($store_info['province_name'])?$store_info['province_name']:'',
                            'city_name'=>!empty($store_info['city_name'])?$store_info['city_name']:'',
                            'area_name'=>!empty($store_info['area_name'])?$store_info['area_name']:'',
                            'address'=>!empty($store_info['address'])?$store_info['address']:'',
                        ],
                        'goods_info'=>!empty($sonList)?$sonList:[],
                    ];
                }
            }
            $data=[
                'total'=>$total,
                'list'=>$new_list,
            ];
            $this->success('',$data,0);
        }catch (Exception $e){
            $msg=$e->getMessage();
            $this->error($msg);
        }
    }


    //门店详情
    public function store(){
        try{
            $store_id=input('store_id','','int');//
            if(empty($store_id)){
                $this->error('门店ID不能为空');
            }

            $info=Db::name('shopro_store')
                ->field('id,name,images,realname,phone,address,store,selfetch,openhours,openweeks')
                ->where(['id'=>$store_id,'status'=>1])
                ->find();

            if(!empty($info)){
                $maps['store_id ']=$store_id;
                $maps['user_id']=$this->auth->id;//当前登录的用户UID
                $sum= Db::name('shopro_order_item')
                    ->field('sum(pay_price)as total_fee,sum(case when wiped_status=3 then 1 else 0 end)as daisum,sum(case when wiped_status=4 then 1 else 0 end)as yisum')
                    ->where($maps)
                    ->find();

                $dai=!empty($sum['daisum'])?$sum['daisum']:'0';
                $yisum=!empty($sum['yisum'])?$sum['yisum']:'0';
                $info['total_income']=!empty($sum['total_fee'])?$sum['total_fee']:'0';
                $info['total_all']=bcadd($dai,$yisum);
                $info['total_wait']=$dai;
            }
            $this->success('success',$info,0);
        }catch (Exception $e){
            $msg=$e->getMessage();
            $this->error($msg);
        }
    }



    //门店管理员
    public function storeUser(){
        try{
            //当前用户管理的门店列表
            $storeIds=Db::name('shopro_user_store')
                ->where(['user_id'=>$this->auth->id])
                ->column('store_id');

            $showLits=[];
            if(!empty($storeIds)){
                //查出门店详情
                $storeList=Db::name('shopro_store')
                    ->field('id,name,images,realname,phone,address,store,selfetch,openhours,openweeks')
                    ->where(['id'=>['in',$storeIds],'status'=>1])
                    ->select();
                if(!empty($storeList)){
                    foreach ($storeList as $k=>$v){
                        $showLits[$k]=$v;
                        $maps['clinc_score_id ']=$v['id'];//门诊店ID
                        $sum= Db::name('shopro_order')
                            ->field('sum(pay_fee)as total_fee,sum(case when status=1 then 1 else 0 end)as daisum,sum(case when status=2 then 1 else 0 end)as yisum')
                            ->where($maps)
                            ->find();
                        $dai=!empty($sum['daisum'])?$sum['daisum']:'0';
                        $yisum=!empty($sum['yisum'])?$sum['yisum']:'0';
                        $showLits[$k]['total_income']=!empty($sum['total_fee'])?$sum['total_fee']:'0';
                        $showLits[$k]['total_all']=bcadd($dai,$yisum);
                        $showLits[$k]['total_wait']=$dai;
                    }
                }
            }
            $this->success('success',$showLits,0);
        }catch (Exception $e){
            $msg=$e->getMessage();
            $this->error($msg);
        }
    }


    //自提单详情
    public function selfetcDetail(){
        $order_id=input('order_id','','int');//核销订单ID
        if(empty($order_id)){
            $this->error('订单ID不能为空！');
        }
        $user_id=$this->auth->id;//当前登录的用户ID
        $detail=Db::name('shopro_order')->field('id,order_sn,user_id,phone,status,consignee,province_name,city_name,area_name,address,pay_fee,total_amount,pay_type,createtime')
            ->where(['id'=>$order_id,'user_id'=>$user_id])->find();
        $arr=[1=>'待自提',2=>'已完成',-1=>'已取消'];
        if(!empty($detail)){
            $order_info=Db::name('shopro_order_item')->field('store_id,goods_title,goods_num,goods_image,goods_price')->where(['order_id'=>$order_id])->select();
            $store_info=[];
            if(!empty($order_info)){
                foreach ($order_info as &$v){
                    $v['goods_image']=cdnurl($v['goods_image']);
                    if(empty($store_info)){
                        $store=Db::name('shopro_store')->field('name,phone,province_name,city_name,area_name,address')->where(['id'=>$v['store_id'],'status'=>1])->find();
                        $store_info=[
                            'store_name'=>!empty($store['name'])?$store['name']:'',
                            'store_phone'=>!empty($store['phone'])?$store['phone']:'',
                            'province_name'=>!empty($store['province_name'])?$store['province_name']:'',
                            'city_name'=>!empty($store['city_name'])?$store['city_name']:'',
                            'area_name'=>!empty($store['area_name'])?$store['area_name']:'',
                            'address'=>!empty($store['address'])?$store['address']:'',
                        ];
                    }
                }
            }
            $detail['status_name']=isset($arr[$detail['status']])?$arr[$detail['status']]:'未知';
            $detail['order_item']=$order_info;
            $detail['store_info']=$store_info;
        }
        $this->success('success',$detail,0);
    }


    //取消订单
    public function orderCancel(){
        try{
            $order_id=input('order_id','','int');//
            $order_note=input('order_note','','trim');//

            if(empty($order_id)){
                $this->error('订单id不能为空',['cancel_status'=>1]);
            }
            if(empty($order_note)){
                $this->error('订单备注不能为空',['cancel_status'=>2]);
            }
            //当前登录用户UID
            $uid=$this->auth->id;
            $info=Db::name('shopro_order')
                ->where(['id'=>$order_id,'user_id'=>$uid])
                ->find();
            if(empty($info)){
                $this->error('订单信息不存在');
            }
            if($info['status']==-1){
                $this->success('success',['cancel_status'=>0],0);
            }
            $info=Db::name('shopro_order')
                ->where(['id'=>$order_id])
                ->update([
                    'status'=>'-1',
                    'remark'=>$order_note,
                    'updatetime'=>time(),
                ]);
            if(!$info){
                $this->error('取消失败',['cancel_status'=>3]);
            }
            $this->success('success',['cancel_status'=>0]);
        }catch (Exception $e){
            $msg=$e->getMessage();
            $this->error($msg);
        }
    }


}